package queue;

public class SeqQueue<T> implements Queue<T> {
    private Object element[];
    // 队头元素下标
    private int front;
    // 队尾后面一个下标，即下一个入队元素的下标
    private int rear;

    public SeqQueue() {
        this(64);
    }

    public SeqQueue(int length) {
        this.element = new Object[length];
        this.front = this.rear = 0;
    }

    @Override
    public boolean isEmpty() {
        return this.front == this.rear;
    }

    @Override
    public boolean add(T x) {
        // 约定队列满： front == (rear + 1) % length， 实际上此时还剩余一个空间。
        if ((this.rear + 1) % this.element.length == this.front) {
            System.out.println("queue is full, return false.");
            return false;
        }
        this.element[this.rear] = x;
        this.rear = (this.rear+1) % this.element.length;
        return true;
    }

    @Override
    public T peek() {
        return this.isEmpty() ? null : (T)this.element[this.front];
    }

    @Override
    public T poll() {
        if (this.isEmpty()) {
            return null;
        }
        T temp = (T)this.element[this.front];
        this.front = (this.front+1) % this.element.length;
        return temp;
    }

    public String toString() {
        String ret = "(";
        for (int i = this.front; i != this.rear; i = (i + 1) % this.element.length) {
            if (i == this.front) {
                ret = ret + this.element[i];
            } else {
                ret = ret + "," + this.element[i];
            }
        }
        ret  = ret + ")";
        return ret;
    }

    public static void main(String args[])
    {
        SeqQueue<Integer> que = new SeqQueue<Integer>();
        que.add(new Integer(10));
        que.add(new Integer(20));
        System.out.println("poll : "+que.poll().toString()+"  "+que.poll().toString()+"  ");
        System.out.println(que.toString());
        que.add(new Integer(30));
        que.add(new Integer(40));
        que.add(new Integer(50));
        que.add(new Integer(60));
        System.out.println(que.toString());
        que.add(new Integer(70));
        System.out.println(que.toString());
    }
}
